package pers.vic.system.system.service;

import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.vic.base.pager.Lookup;
import pers.vic.base.pager.PageInfo;
import pers.vic.base.service.BaseService;
import pers.vic.base.vo.AuthorityData;
import pers.vic.system.model.SysRole;
import pers.vic.system.system.mapper.SysRoleMapper;

/**
 * 角色表 Service
 * 
 * @author VIC
 */
@Service
public class SysRoleService extends BaseService {

	@Resource
	private SysRoleMapper sysRoleMapper;

	/**
	 * 查询列表
	 */
	public PageInfo<SysRole> list(Lookup lookup) {
		startPage(lookup);
		List<SysRole> datas = sysRoleMapper.list(lookup);
		return PageInfo.instance(datas, lookup);
	}

	/**
	 * 根据主键查询
	 */
	public SysRole findById(int id) {
		return sysRoleMapper.findById(id);
	}

	/**
	 * 根据主键数组查询
	 */
	public List<SysRole> findById(int... ids) {
		return sysRoleMapper.findByIds(ids);
	}

	/**
	 * 新增
	 */
	@Transactional
	public int insert(SysRole entity) {
		return sysRoleMapper.insert(entity);
	}

	/**
	 * 修改
	 */
	@Transactional
	public int update(SysRole entity) {
		return sysRoleMapper.update(entity);
	}

	/***
	 * 删除
	 */
	@Transactional
	public int delete(int... ids) {
		return sysRoleMapper.delete(ids);
	}
	
	public List<SysRole> findUserRole(int userId) {
		return sysRoleMapper.findUserRole(userId);
	}
	
	/**获得用户的角色*/
	public List<Integer> getUserRoles(int userId){
		return sysRoleMapper.getUserRoles(userId);
	}

	/**  修改用户的角色*/
	@Transactional
	public void updateUserRole(int userId, int[] roles) {
		Integer[] roleIds = ArrayUtils.toObject(roles);
		AuthorityData data = AuthorityData.instance(getUserRoles(userId), Arrays.asList(roleIds));
		//新建用户和角色按钮关系
		if(!data.getNeedAdd().isEmpty()){
			sysRoleMapper.addUserRole(userId, data.getNeedAdd());
		}
		//删除用户和角色按钮关系
		if(!data.getNeedDelete().isEmpty()){
			sysRoleMapper.deleteUserRole(userId,data.getNeedDelete());
		}
	}

}
